package com.welsy.authoring.business
{
	import mx.rpc.Fault;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.soap.mxml.WebService;	
	import mx.rpc.AbstractOperation;
	import com.adobe.cairngorm.business.ServiceLocator;
	import com.adobe.cairngorm.business.Responder;
	import mx.collections.ArrayCollection;
	import flash.utils.setTimeout;	
	import com.welsy.authoring.vo.CourseVO;
	import com.welsy.user.model.UserModelLocator;
		

	/**
	  * Delegate for published courses retrieval
	  * @author Welsy.org
	  * @version	$Revision: 1.1 $
	 */
	public class GetCoursesPublishDelegate
	{
		
		/**
		  * Delegate initialization for published course retrieval
		  * @param responder The event handler fo the server response
		  */
		public function GetCoursesPublishDelegate( responder : Responder )
		{		
			this.service = ServiceLocator.getInstance().getWebService("CourseService") as WebService;
			this.responder = responder;
		}
		
		/**
		  * Init the chain for throwing the request
		  */
		public function getCourses() : void
		{	
			getRealCourses();
		}
						
		/**
		  * Invoke the request and send it to the server
		  */
		private function getRealCourses() : void
		{			
			var o:AbstractOperation = service.getOperation("GetPublishCourses");
			o.arguments.GetPublishCoursesRequest.AuthorID = UserModelLocator.getInstance().authorId;
			o.addEventListener(ResultEvent.RESULT, GetPublishCourses_onResult);
			o.addEventListener(FaultEvent.FAULT, GetPublishCourses_onFault);
			service.GetPublishCourses();			
		}	
		
		 
		/**
		  * Read the server response
		  * @param event The server SOAP response
		  */
		private function GetPublishCourses_onResult(event:ResultEvent):void
		{
			var coursesXMLList:XMLList = event.result as XMLList;
			var courses : ArrayCollection = new ArrayCollection();
			courses = parseXMLCourses(coursesXMLList)						
			responder.onResult(courses);
		}
		
		/**
		  * Parse the XML course representation
		  * @param list The XML course representation
		  * @return The parsed server response, ie a list of curses
		  */
		private function parseXMLCourses(list:XMLList):ArrayCollection
		{
			var courses : ArrayCollection = new ArrayCollection();
			var item:XML;
					
			list = list.descendants(CourseQNames.qnCourses).children();
			for each(item in list) {            	
            	var courseVO:CourseVO = new CourseVO;
				courseVO.setProperties(item);
				courses.addItem(courseVO);            	            	
   			}
   			return courses;
		}
		
		/**
		  * The fault handler
		  * @param event The fault event, for both clientside and serverside errors
		  */
		private function GetPublishCourses_onFault(event:FaultEvent):void
		{	
			responder.onFault();		
		}	
	
		private var responder : Responder;
		private var service : WebService;
	}

}